package cn.Aop;

import cn.CommonUtils.SignatureJwtUtils;
import cn.MetaData.Annotation.SignatureJwt;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

    @Component
    @Aspect
    @Slf4j
    public class FrontendInterfaceSignatureAop {

        /**
         * 注解切点
         * 带参
         */
        @Pointcut(value = "@annotation(cn.MetaData.Annotation.SignatureJwt) && args(..)" )
        public void PointcutAnnotationWithParameter(){}

        /**
         * 带参 关注点对象 处理JWT
         * 需要把jwt放在最后一个参数
         * @param proceedingJoinPoint
         * @return
         */
        @Around(value = "PointcutAnnotationWithParameter()")
        public Object oneParamBeforeHandlerByAnnoWithParam2(ProceedingJoinPoint proceedingJoinPoint ){

            log.info("$$$$$$$$$$$$$$$$$$$$$$ 注解切点 抓取关注点参数 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
            log.info("Come in Aop Procduce : "+ "powerd by annotation" + " JoinPoint");

            String jwtSignature = (String) proceedingJoinPoint.getArgs()[proceedingJoinPoint.getArgs().length - 1 ];

            if (StringUtils.isEmpty(jwtSignature)) {
                JSONObject result = new JSONObject();
                result.put("status", "invail login");
                return result;
            }

            Claims claims = SignatureJwtUtils.translateJWT(jwtSignature, "secret", SignatureAlgorithm.HS384, 30 * 60 * 1000L);
            if (claims == null) {
                JSONObject result = new JSONObject();
                result.put("status", "invail login claims is null");
                return result;
            }

            log.info("$$$$$$$$$$$$$$$$$$$$$$ 注解切点 抓取关注点参数 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");

            try {
                Object result = proceedingJoinPoint.proceed();
                return result;
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            return null;
        }

    }
